package DoubleLinkedList;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ratuil
 * Date: 26.02.13
 * Time: 17:34
 * To change this template use File | Settings | File Templates.
 */
public class DoubleLinkedList<T> implements List<T> {
    /**
    * The first element in the list.
    */

    private Node<T> first;
    /**
    * The last element in the list.
    */

    private Node<T> last;
    /**
    * The current length of the list.
    */
    int size = 0;

    public DoubleLinkedList(){}
    public DoubleLinkedList(Collection<? extends T> c) {
        this();
        addAll(c);
    }
    /**
    * Class to represent an entry in the list. Holds a single element.
    */
    private static final class Node<T>{
        /** The next list entry, null if this is last. */
        Node<T> next;

        /** The previous list entry, null if this is first. */
        Node<T>previous;

        /** The element in the list. */
        T data;

        /**
        * Construct an entry.
        * @param data the list element
        */
        public Node (T data){
            this.data = data;
        }
        public Node(Node<T>previous,T data,Node<T>next){
            this.data=data;
            this.next = next;
            this.previous = previous;
        }
    }

    /**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public T getFirst() {
        final Node<T> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.data;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public T getLast() {
        final Node<T> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.data;
    }



    /**
     * @param n the number of the entry to get
     * @return the entry at position n
     */
     // Package visible for use in nested classes.
    Node<T>getNode(int n){
        Node<T>e;
        if(n<size/2){
            e=first;
            // n less than size/2, iterate from start
            while(n-->0)e=e.next;
        }else{
            e=last;
            // n greater than size/2, iterate from end
            while(++n<size)e=e.previous;
        }
        return e;
    }


    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        if(first==null)return true;
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    @Override
    public Iterator<T> iterator() {
        return new DescendingIterator();
    }

    @Override
    public Object[] toArray() {
        Object[] result = new Object[size];
        int i = 0;
        for (Node<T> x = first; x != null; x = x.next)
            result[i++] = x.data;
        return result;
    }

    @Override
    public <T1 extends Object> T1[] toArray(T1[] a) {
        if (a.length < size)
            a = (T1[])java.lang.reflect.Array.newInstance(
                    a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        for (Node<T> x = first; x != null; x = x.next)
            result[i++] = x.data;

        if (a.length > size)
            a[size] = null;

        return a;
    }

    @Override
    public boolean add(T t) {
        final Node<T> l = last;
        final Node<T> newNode = new Node<T>(l, t, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        //modCount++;
        return true;  //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * Unlinks non-null node x.
     */
    T unlink(Node<T> x) {
        // assert x != null;
        final T element = x.data;
        final Node<T> next = x.next;
        final Node<T> prev = x.previous;

        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.previous = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.previous = prev;
            x.next = null;
        }

        x.data = null;
        size--;
        //modCount++;
        return element;
    }
    @Override
    public boolean remove(Object o) {
        if (o == null) {
            for (Node<T> x = first; x != null; x = x.next) {
                if (x.data == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<T> x = first; x != null; x = x.next) {
                if (o.equals(x.data)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean addAll(Collection<? extends T> c) {
        return addAll(size, c);
    }

    @Override
    public boolean addAll(int index, Collection<? extends T> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<T> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.previous;
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") T e = (T) o;
            Node<T> newNode = new Node<T>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.previous = pred;
        }

        size += numNew;
        //modCount++;
        return true;
    }

    /**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<T> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node<T> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<T> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.previous;
            return x;
        }
    }

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * Tells if the argument is the index of a valid position for an
     * iterator or an add operation.
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * Removes all of the elements from this list.
     * The list will be empty after this call returns.
     */
    @Override
    public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        for (Node<T> x = first; x != null; ) {
            Node<T> next = x.next;
            x.data = null;
            x.next = null;
            x.previous = null;
            x = next;
        }
        first = last = null;
        size = 0;
        //modCount++;
    }

    @Override
    public T get(int index) {
        checkElementIndex(index);
        return node(index).data;
    }

    @Override
    public T set(int index, T element) {
        checkElementIndex(index);
        Node<T> x = node(index);
        T oldVal = x.data;
        x.data = element;
        return oldVal;
    }

    @Override
    public void add(int index, T element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

    /**
     * Links e as last element.
     */
    void linkLast(T e) {
        final Node<T> l = last;
        final Node<T> newNode = new Node<T>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        //modCount++;
    }

    /**
     * Inserts element e before non-null Node succ.
     */
    void linkBefore(T e, Node<T> succ) {
        // assert succ != null;
        final Node<T> pred = succ.previous;
        final Node<T> newNode = new Node<T>(pred, e, succ);
        succ.previous = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        //modCount++;
    }

    @Override
    public T remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

    @Override
    public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<T> x = first; x != null; x = x.next) {
                if (x.data == null)
                    return index;
                index++;
            }
        } else {
            for (Node<T> x = first; x != null; x = x.next) {
                if (o.equals(x.data))
                    return index;
                index++;
            }
        }
        return -1;
    }

    @Override
    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<T> x = last; x != null; x = x.previous) {
                index--;
                if (x.data == null)
                    return index;
            }
        } else {
            for (Node<T> x = last; x != null; x = x.previous) {
                index--;
                if (o.equals(x.data))
                    return index;
            }
        }
        return -1;
    }

    @Override
    public ListIterator<T> listIterator() {
        return new ListItr(0);
    }

    @Override
    public ListIterator<T> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }

    @Override
    public List<T> subList(int fromIndex, int toIndex) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    private class DescendingIterator implements Iterator<T> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public T next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

    private class ListItr implements ListIterator<T> {
        private Node<T> lastReturned = null;
        private Node<T> next;
        private int nextIndex;
        //private int expectedModCount = modCount;

        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }

        public boolean hasNext() {
            return nextIndex < size;
        }

        public T next() {
            //checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.data;
        }

        public boolean hasPrevious() {
            return nextIndex > 0;
        }

        public T previous() {
            //checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.previous;
            nextIndex--;
            return lastReturned.data;
        }

        public int nextIndex() {
            return nextIndex;
        }

        public int previousIndex() {
            return nextIndex - 1;
        }

        public void remove() {
            //checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<T> lastNext = lastReturned.next;
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            //expectedModCount++;
        }

        public void set(T t) {
            if (lastReturned == null)
                throw new IllegalStateException();
            //checkForComodification();
            lastReturned.data = t;
        }

        public void add(T t) {
            //checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(t);
            else
                linkBefore(t, next);
            nextIndex++;
            //expectedModCount++;
        }
    }
}
